package com.woyou.ui.activity;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;

import retrofit.RetrofitError;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.citaq.ideliver.R;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.sso.UMSsoHandler;
import com.woyou.Constant;
import com.woyou.bean.CodeResult;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.CheckUpdateReq;
import com.woyou.bean.rpc.CheckUpdateRes;
import com.woyou.model.UserModel;
import com.woyou.service.LocationLoopService;
import com.woyou.service.NetWorkCenter;
import com.woyou.service.location.BaiduLocationService;
import com.woyou.ui.component.CheckUpdateDialog;
import com.woyou.utils.DeviceUtils;
import com.woyou.utils.LogUtil;
import com.woyou.utils.ParseUtils;
import com.woyou.utils.eventbus.EventHideUpdate;
import com.woyou.utils.eventbus.EventShowBar;

import de.greenrobot.event.EventBus;

/**
 * 主界面
 * 
 * @author longtao.li
 * 
 */
@EActivity
public class HomeActivity extends SuperFragmentActivity {
	
	private static final String TAG = "HomeActivity";
	
	private long exitTime = 0;
	double lat = 0;
	double lng = 0;
	
	@Bean HomeActivityPresenter mController;
	@Bean UserModel mUserModel;
	@Bean BaiduLocationService mBaiduLocationService;
	private MyLocationListener mListener;
	BDLocation mlocation;
	private final UMSocialService uMSocialService = UMServiceFactory.getUMSocialService(Constant.DESCRIPTOR);

	public static boolean isShow = true;

	private CheckUpdateDialog checkDialog;

	public ImageView homeImage;
	public ImageView homeShops;
	public ImageView homeMine;
	
	@SuppressWarnings("rawtypes")
	private Class gotoClass; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_home);

		EventBus.getDefault().register(this);
		
		mController.onCreate(this);
		
		mListener = new MyLocationListener();
		mBaiduLocationService.registerLocationListenner(mListener);
		mBaiduLocationService.startLocation();
		
		checkDialog = new CheckUpdateDialog();
		initView();
	}
	
	/**得到传递的数据*/
	@SuppressWarnings("rawtypes")
	private void getData(){
		if(hasInfo()){
			gotoClass = (Class) mInfo.getData();
		}
	}

	private void initView() {
		homeImage = (ImageView) findViewById(R.id.home_index_iv);
		homeShops = (ImageView) findViewById(R.id.home_shops_iv);
		homeMine = (ImageView) findViewById(R.id.home_mine_iv);
	}

	/**
	 * 接受的事件
	 * 
	 * @param event
	 */
	public void onEvent(EventShowBar event) {
		checkDialog.dismiss();
		int id = event.id;
		if (id == 1) {
			homeImage.setImageResource(R.raw.home_index_p);
			homeShops.setImageResource(R.raw.home_shops);
			homeMine.setImageResource(R.raw.home_mine);
		} else if (id == 2) {
			homeImage.setImageResource(R.raw.home_index);
			homeShops.setImageResource(R.raw.home_shops_p);
			homeMine.setImageResource(R.raw.home_mine);
		} else if (id == 3) {
			homeImage.setImageResource(R.raw.home_index);
			homeShops.setImageResource(R.raw.home_shops);
			homeMine.setImageResource(R.raw.home_mine_p);
		}
	}

	public void onEvent(EventHideUpdate event) {
		checkDialog.dismiss();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mController.onActivityPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		LogUtil.d(TAG, "onResume()");
		getData();
		if(gotoClass!=null){
			mController.showFragment(gotoClass.getName());
		}
		setIntent(null);
		mController.onActivityResume(this);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mController.onActivityDestory();
		// 解除广播
		unregisterReceiver(broadcastReceiver);
		EventBus.getDefault().unregister(this);
	}

	@Override
	public void retry() {

	}

	/**
	 * tab点击事件
	 * 
	 * @param v
	 */
	public void tabOnclick(View v) {
		mController.tabOnclick(v);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // 按下的如果是BACK，同时没有重复
			boolean flag = mController.backFm();
			if (!flag) {
				if ((System.currentTimeMillis() - exitTime) > 2000) {
					exitTime = System.currentTimeMillis();
					Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
					exitTime = System.currentTimeMillis();
				} else {
					// CustomExitDialog exitDialog = new CustomExitDialog(mContext, R.style.customExitDailogStyle, R.layout.custom_exit_dialog);
					// exitDialog.show();
					LocationLoopService.getInstance(mContext).clear(); // 清空手动选的地址
					finish();
					// System.exit(0);
				}
			}
		}
		return true;
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() != KeyEvent.ACTION_UP) {
			Log.i(TAG, "dispatchKeyEvent:" + event.getKeyCode());
			boolean flag = mController.handleKeyEvent(event);
			if (flag) {
				return true;
			}
		}
		return super.dispatchKeyEvent(event);
	}

	@SuppressWarnings("unused")
	@Background
	void checkUpdate(BDLocation location) {
		if (location == null) {
			return;
		}
		if (!NetWorkCenter.isNetworkConnected(this)) {
			showToast("请检查你的网络!");
			return;
		}
		try {
			UserInfo userInfo = mUserModel.getUserInfo();
			CheckUpdateReq checkUpdateReq = new CheckUpdateReq();
			checkUpdateReq.setuId(userInfo.getuId());
			checkUpdateReq.setPwd(userInfo.getPwd());
			checkUpdateReq.setCityName(userInfo.getCity().getCity());
			checkUpdateReq.setDeviceInfo(DeviceUtils.getDeviceInfo(mContext));
			lat = mBaiduLocationService.getLastLocation().getLatitude();
			lng = mBaiduLocationService.getLastLocation().getLongitude();
			if (location == null) {
				checkUpdateReq.setLat("");
				checkUpdateReq.setLng("");
			} else {
				checkUpdateReq.setLat(location.getLatitude() + "");
				checkUpdateReq.setLng(location.getLongitude() + "");
			}
			checkUpdateReq.setDeviceType("AD_VERSION");
			checkUpdateReq.setVersionCode(Constant.currentVersion);
			CodeResult<CheckUpdateRes> reuslt = mUserModel.checkUpdate(checkUpdateReq);
			showView(reuslt);
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case HTTP:
				showToast("很遗憾，网路不给力！");
				return;
			case CONVERSION:
				showToast("很抱歉，服务器又任性了！");
				return;
			case NETWORK:
				showToast("很遗憾，网路不给力！");
				return;
			case UNEXPECTED:
				showToast("很抱歉，服务器又任性了！");
				return;
			}
		}
	}

	@UiThread
	void showView(CodeResult<CheckUpdateRes> reuslt) {
		if (reuslt != null) {
			CheckUpdateRes checkUpdateRes = reuslt.getBean();
			if (checkUpdateRes != null && checkUpdateRes.getIsUpdate() > 0) {
				mUserModel.setUpdateNum(mUserModel.getUpdateNum() + 1);
				checkDialog.Dialog(mContext, checkUpdateRes.getVersionName(),
						(int) (checkUpdateRes.getSize() / 1024) + "M",
						ParseUtils.convertTime(checkUpdateRes.getReleaseTime() * 1000, "yyyy年MM月dd日") + "发布",
						checkUpdateRes.getUpdateInfo().replace("<LF>", "\n"), checkUpdateRes.getDownloadUrl());
			}
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 2:
				mUserModel.setUpdateNum(0);
				showToast("我有外卖安装完成");
				break;
			}
		}

	};

	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("android.intent.action.PACKAGE_ADDED");
		intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
		intentFilter.addDataScheme("package");
		// 注册一个广播
		registerReceiver(broadcastReceiver, intentFilter);
	}

	// 接收到安装完成apk的广播
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Message message = handler.obtainMessage();
			message.what = 2;
			handler.sendMessage(message);
		}
	};

	class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			mBaiduLocationService.stop();
			mBaiduLocationService.unRegisterLocationListener(mListener);
			Log.i("onReceiveLocation", "onPageFinished");
			if (location != null) {
				mlocation = location;
				if (isShow) {
					if (mUserModel.getUpdateNum() < 2) {
						checkUpdate(mlocation);
					}
				} else {
					isShow = true;
					System.out.println("3==" + HomeActivity_.isShow);
				}
			}
		}
	}

	@Override
	public void netError() {

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = uMSocialService.getConfig().getSsoHandler(requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

}
